package com.sencorsta.ids.core.tcp.websocket;

import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.ids.core.tcp.socket.protocol.Header;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.Arrays;
import java.util.List;

/**
 * 请求消息解码类
 * @author ICe
 */
public final class WebSocketDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {
	private static int __RESPONSE_MAX_LEN = Integer.MAX_VALUE;

	@Override
	protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame binaryWebSocketFrame, List<Object> list) throws Exception {
		ByteBuf in=binaryWebSocketFrame.content();
		if(in.readableBytes() < Header.SIZE) {
			return;
		}
		in.markReaderIndex();

		byte[] temp=new byte[in.readableBytes()];
		in.readBytes(temp);
		Out.trace("收到数据:",Arrays.toString(temp),"总长度",temp.length);
		in.resetReaderIndex();


		in.readShort();
		int len=in.readInt();
		Out.trace("长度:",len);
		if (len > __RESPONSE_MAX_LEN || len < 0) {
			Channel session = ctx.channel();
			Out.warn("包体长度错误");
			session.close();
			return;
		}
		if (in.readableBytes() < len) {
			in.resetReaderIndex();
			return;
		}
		in.resetReaderIndex();
		OpenMessage msg=new OpenMessage();
		msg.decode(in);
		msg.channel=ctx.channel();
		list.add(msg);
	}


}
